package com.tnsw.noxnox.db;

import java.io.File;
import com.tnsw.coreutils.files.FileUtils;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;
import android.provider.ContactsContract.Directory;
import android.util.Log;

public class DBManagerBase extends SQLiteOpenHelper {
	
	private static String DB_BASE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
	private static String DB_DIRECTORY = "com.tnsw.noxnox";
	private static String DB_FILE = "noxnoxdb.s3db";
	private static boolean REPLACED_FROM_ASSET = false;
	private String baseDir = DB_BASE_PATH + DB_DIRECTORY + "/";
	private String fullDBPath = baseDir + DB_FILE;
	
	protected String tag = "DBManagerBase";
	protected Context context;
	
	public DBManagerBase(Context context) {
		super(context, "", null, 1);
		this.context = context;
		
		this.initialize();
		int version = this.checkVersion();
		Log.d(tag, "This DB version=" + version);
		
		int primarykey = this.getNewPrimarykey();
		Log.d(tag, "primarykey=" + primarykey);
				
		//String currentDBFile = this.context.getDatabasePath(DB_FILE).getAbsolutePath();
		//Log.d(tag, "currentDBFile=" + currentDBFile);		
				
	}
	
	private void initialize() {
		//String baseDir = DB_BASE_PATH + DB_DIRECTORY + "/";
		//String fullDBPath = baseDir + DB_FILE;
		boolean directoryOK = false;
		
		Log.d(tag, "baseDir=" + baseDir);
		Log.d(tag, "fullDBPath=" + fullDBPath);
		
		File dir = new File(baseDir);
		if (dir.exists() == false) {
			Log.d(tag, "Not found directory for DB: " + DB_BASE_PATH + DB_DIRECTORY + ", going to create");
			
			try {
				boolean b = dir.mkdir();
				if (b == true) {
					Log.d(tag, "created directory for DB: " + baseDir);
					directoryOK = true;
				} else {
					Log.e(tag, "failed to create directory for DB: " + baseDir);
				}
					
			} catch (Exception e) {
				Log.e(tag, "Exception on creating directory '" + baseDir + "'", e);
			}
			
			
		} else {  // baseDir exists, now working for db file
			directoryOK = true;
			
		}
		
		Log.d(tag, "directoryOK=" + directoryOK);
			
		if (directoryOK == true) {
			File f = new File(fullDBPath);
			if (f.exists() == false) {
				Log.d(tag, "Not found existing DB: " + fullDBPath);
				try {					
					FileUtils.copyFile(this.context.getAssets().open(DB_FILE), fullDBPath);
					Log.d(tag, "Copied from asset to " + fullDBPath + " successfully");
				} catch (Exception e) {
					Log.e(tag, "Error copying from asset to '" + fullDBPath + "'", e);
				}
				
			} else { // DB file exists, choose whether to overwrite?
				Log.d(tag, "REPLACE_FROM_ASSET=" + REPLACED_FROM_ASSET);
				if (REPLACED_FROM_ASSET) {
					try {
						File deleteFile = new File(fullDBPath);
						deleteFile.delete();
						Log.d(tag, "Deleted " + fullDBPath);
					
						FileUtils.copyFile(this.context.getAssets().open(DB_FILE), fullDBPath);
						Log.d(tag, "Copied successfully from asset to " + fullDBPath);
					} catch (Exception e) {
						Log.e(tag, "Error replace from asset to '" + fullDBPath + "'", e);
					}
				} else {
					Log.d(tag, "Not replace db from asset");
				}
			}
			
			
		} else {
			Log.e(tag, "directoryOK==false, cannot create/connect database due to directory problem");
		}
	}
	
	public String getFullDatabasePath() {
		return(this.fullDBPath);
	}
	
	public int getNewPrimarykey() {
		int primarykey = 0;
		SQLiteDatabase db = null;
		
		try {
			db = this.getWritableDatabase();
			//db.beginTransactionNonExclusive();
			db.execSQL("update dbinfo set id=id+1");
			
			Cursor cursor = db.rawQuery("select id from dbinfo", null);
			if (cursor.getCount() != 0) {
				cursor.moveToFirst();
				primarykey = cursor.getInt(0);
			}
			cursor.close();
			
			
			//db.setTransactionSuccessful();
			//db.endTransaction();
			//Log.d(tag, "committed");
			
		} catch (Exception e) {
			Log.e(tag, "getNewPrimarykey() - " + e.toString(), e);
			if (db != null) {
				if (db.inTransaction() == true) {
					//db.endTransaction();
				}	
			}
			
		}
		
		if (db != null) {
			db.close();			
		}
		
		return(primarykey);
	}
	
	private int checkVersion() {
		int version = -1;
		SQLiteDatabase db = null;
		
		try {
			db = this.getWritableDatabase();
			
			Cursor cursor = db.rawQuery("select * from dbinfo", null);
			if (cursor.getCount() != 0) {
				cursor.moveToFirst();
				version = cursor.getInt(0);
			}
			cursor.close();
		} catch (Exception e) {
			Log.e(tag, "checkVersion() - " + e.toString(), e);
		}
		
		if (db != null) {
			db.close();
		}
		
		return(version);
	}
	


	@Override
	public void onCreate(SQLiteDatabase db) {
		Log.d(tag, "onCreate()");
	}
	
	@Override
	public void onOpen(SQLiteDatabase db) {
		super.onOpen(db);
		Log.d(tag, "onOpen()");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		Log.d(tag, "onUpgrade(oldVersion=" + oldVersion + ", newVersion=" + newVersion);
	}
	
	@Override
	public SQLiteDatabase getReadableDatabase()
	{
	    SQLiteDatabase database = SQLiteDatabase.openDatabase(this.fullDBPath, null, SQLiteDatabase.OPEN_READONLY);
	    return database;
	}

	@Override
	public SQLiteDatabase getWritableDatabase()
	{
	    SQLiteDatabase database = SQLiteDatabase.openDatabase(this.fullDBPath, null, SQLiteDatabase.OPEN_READWRITE);
	    return database;
	}
	
	

}
